# -*- coding: utf-8 -*-
# @Time : 2022/8/20 17:07
# @Author : WangYunfei
# @FileName: main.py
# @Email: lxb_wyf@163.com
import time
from io import BytesIO
from PIL import Image
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By


class FontsToImage(object):

    def __init__(self):
        # 设置屏蔽
        options = webdriver.ChromeOptions()
        options.add_argument('--disable-blink-features=AutomationControlled')

        options.add_argument('headless')
        self.browser = webdriver.Chrome(options=options)
        self.browser.maximize_window()
        # 将浏览器最大化显示
        self.action = ActionChains(self.browser)

        self._top = 0
        self.deviation_top = 10

    def get_url(self, url_path):
        self.browser.get(url_path)

        # 接下来是全屏的关键，用js获取页面的宽高，如果有其他需要用js的部分也可以用这个方法
        width = self.browser.execute_script("return document.documentElement.scrollWidth")
        height = self.browser.execute_script("return document.documentElement.scrollHeight")
        print(width, height)
        # 将浏览器的宽高设置成刚刚获取的宽高  如果宽度不够，可以自定义宽度，宽度自己调整
        self.browser.set_window_size(width, height)
        time.sleep(1)
        # 截图并关掉浏览器   保存的pic_name 是 png 结尾的  绝对路径
        self.browser.save_screenshot(r"D:\Python\Projects\tuling-code\example\automate\font_img\1.png")
        # self.browser.close()

        li_list = self.browser.find_elements(By.XPATH, '//ul[@class="iconfont-list"]/li')
        for li in li_list:
            name = li.find_element(By.XPATH, './div[@class="name"]').text
            self.save_img(li.find_element(By.XPATH, './i'), name)
            print(name)

    def save_img(self, element, file_name):
        self.action.move_to_element(element).perform()
        location = element.location  # 初始坐标(左上角) # {'x': 0, 'y': 164}
        size = element.size    # 高和宽  # {'height': 260, 'width': 390}
        top, bottom, left, right = location["y"], location["y"] + size["height"], location["x"], location["x"] + size["width"]
        top, bottom, left, right = self.xyz(top, bottom, left, right)
        screenshot = self.browser.get_screenshot_as_png()  # 截取整个浏览显示页面
        img = Image.open(BytesIO(screenshot))
        img2 = img.crop((left, top, right, bottom))

        img.save("11.png")
        img2.save(f"./image/{file_name}.png")

    def xyz(self, top, bottom, left, right):
        top, bottom, left, right = top + 10, bottom - 17, left - 5, right + 5
        return top, bottom, left, right

    def __del__(self):
        self.browser.quit()


if __name__ == '__main__':
    url = r"file:///C:/Users/wyf/Desktop/fonteditor/example.html"
    FontsToImage().get_url(url)

